/**
 * 渠道发布，快捷操作
 */
import React from 'react';
import { Form, Modal, Checkbox, Menu, Dropdown, message, Spin } from 'antd';
import { useRequest } from '@/hooks';
import AuthComponent from '@/utils/auth/AuthComponent';
import helper from '@/utils/auth/helper';
import { DemandFieldUpdate } from '@/pages/Recruitment/Channel/containers';
import { Icon } from '../components';
import { useChannelError, useChannelOnlineCheck, useChannelQuick } from '../hooks';
import { fetchChannelOutwards } from '../service';
import { SelectChannel } from './channel';

const { checkCode } = helper;

const formItemLayout = {
    labelCol: {
        sm: { span: 5 }
    },
    wrapperCol: {
        sm: { span: 19 }
    }
};

const releaseTag = {
    0: <span style={{ marginLeft: 8 }}>[未发布]</span>,
    1: <span style={{ marginLeft: 8 }}>[已发布]</span>,
    2: <span style={{ marginLeft: 8 }}>[待审核]</span>,
    3: <span style={{ marginLeft: 8 }}>[已下线]</span>
};

function DemandPublishQuick({ data = {}, form, onSuccess = () => {}, ...rest }) {
    const { data: rawData, run, loading } = useRequest(fetchChannelOutwards, {
        manual: true
    });
    const { update, online, offline, release } = useChannelQuick();
    const { checkError } = useChannelError();
    const defaultValueInitRef = React.useRef(null);

    const isPublished = data.outChannelReleaseNum + data.innerChannelReleaseNum > 0;

    // 不同操作对应配置
    const config = {
        release: { title: '一键发布', request: release },
        update: { title: '更新', request: update },
        online: { title: '上线', request: online },
        offline: { title: '下线', request: offline }
    };

    const [visible, setVisible] = React.useState();
    const [mode, setMode] = React.useState('release');

    const { check } = useChannelOnlineCheck({ channelCompanyCode: data.companyCode });

    const channelData = React.useMemo(() => {
        const { inwardChannelList = [], outwardChannelList = [] } = rawData?.data || {};

        // 招聘网站
        const webs = outwardChannelList.filter(item => Number(item.channelType) === 2) || [];
        // 猎头公司
        const companies = outwardChannelList.filter(item => Number(item.channelType) === 3) || [];

        return {
            outer: { webs, companies },
            inner: inwardChannelList
        };
    }, [rawData]);

    const [websSelections, setWebsSelections] = React.useState([]);
    const [innerSelections, setInnerSelections] = React.useState([]);
    const [companiesSelections, setCompaniesSelections] = React.useState([]);
    const [checkedWeb, setCheckedWeb] = React.useState(true);
    const [checkedCompany, setCheckedCompany] = React.useState(true);

    const [submitting, setSubmitting] = React.useState(false);
    const handleRelease = async () => {
        let finalSelections = [...innerSelections];

        if (checkedWeb) {
            finalSelections = [...finalSelections, ...websSelections];
        }

        if (checkedCompany) {
            finalSelections = [...finalSelections, ...companiesSelections];
        }

        if (finalSelections.length === 0) {
            message.warning('请至少选择一项发布渠道！');
            return;
        }

        setSubmitting(true);
        if (config[mode]) {
            const res = await config[mode].request({ channelCodeList: finalSelections, recruitCode: data.recruitCode });
            if (res?.code === 10000) {
                const error = await checkError(res, data);
                if (!error) {
                    message.success(res.msg || '操作成功');
                    onSuccess();
                }
            }
        }
        setSubmitting(false);
    };

    const callCheck = async () => {
        const checked = await check();
        if (checked) {
            run({ outwardId: data.outwardId });
            defaultValueInitRef.current = false;
            setVisible(true);
        }
    };

    const [checking, setChecking] = React.useState(false);
    const handleMenu = _mode => async () => {
        if (checking) {
            return;
        }
        setChecking(true);
        await callCheck();
        setChecking(false);
        setMode(_mode);
    };

    const menuPublished = (
        <Menu>
            <Menu.Item onClick={handleMenu('release')} disabled={!checkCode('office:recruitment:channel:publish')}>
                一键发布
            </Menu.Item>

            <Menu.Item onClick={handleMenu('offline')} disabled={!checkCode('office:recruitment:channel:offline')}>
                下线
            </Menu.Item>

            <Menu.Item onClick={handleMenu('online')} disabled={!checkCode('office:recruitment:channel:online')}>
                上线
            </Menu.Item>
        </Menu>
    );

    const menu = (
        <Menu>
            <Menu.Item onClick={handleMenu('release')} disabled={!checkCode('office:recruitment:channel:publish')}>
                一键发布
            </Menu.Item>
        </Menu>
    );

    const innerData = channelData?.inner?.map(item => {
        const disabledMap = {
            release: ![0].includes(item.releaseStatus),
            update: item.releaseStatus !== 1,
            online: item.releaseStatus !== 3,
            offline: item.releaseStatus !== 1
        };
        return {
            label: (
                <span>
                    {item.channelName}
                    {releaseTag[item.releaseStatus]}
                    {item.channelStatus === 0 && '[已禁用]'}
                </span>
            ),
            value: item.channelCode,
            disabled: item.channelStatus === 0 || disabledMap[mode]
        };
    });

    React.useEffect(() => {
        if (!defaultValueInitRef.current && innerData.length !== 0) {
            const selections = innerData?.filter(item => !item.disabled).map(item => item.value);
            setInnerSelections(selections);
            defaultValueInitRef.current = true;
        }
    }, [innerData]);

    return (
        <>
            <AuthComponent code="office:recruitment:channel">
                <Dropdown overlay={isPublished ? menuPublished : menu} placement="bottomCenter">
                    <Icon title="渠道发布" type="qudaofabu" {...rest} />
                </Dropdown>
            </AuthComponent>

            <Modal
                width={600}
                title={config[mode].title}
                visible={visible}
                onOk={handleRelease}
                onCancel={() => {
                    setVisible(false);
                }}
                confirmLoading={submitting}
                destroyOnClose
                afterClose={() => {
                    setWebsSelections([]);
                    setInnerSelections([]);
                    setCompaniesSelections([]);
                }}
            >
                <Spin spinning={loading}>
                    { ['release', 'online', 'update'].includes(mode)
                        ? <DemandFieldUpdate style={{ marginBottom: 16 }} outwardId={data?.outwardId}/>
                        : null
                    }
                    <Form {...formItemLayout}>
                        <Form.Item label="外部渠道">
                            <div style={{ display: 'flex', alignItems: 'center', marginBottom: 16 }}>
                                <Checkbox
                                    checked={checkedWeb}
                                    onChange={() => {
                                        setCheckedWeb(!checkedWeb);
                                    }}
                                />
                                <span style={{ padding: '0 8px' }}>招聘网站</span>
                                <SelectChannel
                                    type="web"
                                    mode={mode}
                                    loading={loading}
                                    treeCheckable
                                    disabled={!checkedWeb}
                                    data={channelData?.outer?.webs}
                                    value={websSelections}
                                    onChange={value => {
                                        setWebsSelections(value);
                                    }}
                                />
                            </div>
                            <div style={{ display: 'flex', alignItems: 'center' }}>
                                <Checkbox
                                    checked={checkedCompany}
                                    onChange={() => {
                                        setCheckedCompany(!checkedCompany);
                                    }}
                                />
                                <span style={{ padding: '0 8px' }}>猎头公司</span>
                                <SelectChannel
                                    mode={mode}
                                    loading={loading}
                                    treeCheckable
                                    disabled={!checkedCompany}
                                    data={channelData?.outer?.companies}
                                    value={companiesSelections}
                                    onChange={value => {
                                        setCompaniesSelections(value);
                                    }}
                                />
                            </div>
                        </Form.Item>
                        {innerData.length !== 0 && (
                            <Form.Item label="内部渠道">
                                <Checkbox.Group
                                    options={innerData}
                                    value={innerSelections}
                                    onChange={value => {
                                        setInnerSelections(value);
                                    }}
                                />
                            </Form.Item>
                        )}
                    </Form>
                </Spin>
            </Modal>
        </>
    );
}

export default Form.create()(DemandPublishQuick);
